<style><!DOCTYPE html>
    .upload-status {
        position: fixed;
        bottom: 20px;
        right: 20px;
        padding: 10px 15px;
        background: var(--card-bg);
        border-radius: 8px;
        box-shadow: 0 4px 12px rgba(0,0,0,0.15);
        z-index: 1000;
        display: flex;
        align-items: center;
        gap: 8px;
    }
    .upload-status i {
        font-size: 18px;
    }
</style>

<html lang="en">
<head>
    <title>{% if post %}Edit{% else %}New{% endif %} Post</title>
    <link rel="stylesheet" href="{{ url_for('static', filename='style.css') }}">
    <link href="https://cdn.jsdelivr.net/npm/tui-editor@1.4.10/dist/tui-editor.min.css" rel="stylesheet">
    <link href="https://cdn.jsdelivr.net/npm/tui-editor@1.4.10/dist/tui-editor-contents.min.css" rel="stylesheet">
    <link href="https://cdn.jsdelivr.net/npm/codemirror@5.65.2/lib/codemirror.min.css" rel="stylesheet">
    <link href="https://cdn.jsdelivr.net/npm/highlight.js@9.12.0/styles/github.min.css" rel="stylesheet">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
</head>
<body class="apple-style">
    <div class="top-navbar" style="position: sticky; top: 0; width: 100%; z-index: 100; background: rgba(255,255,255,0.98); box-shadow: 0 2px 10px rgba(0,0,0,0.1);">
        <div class="nav-left">
            <a href="{{ url_for('admin.admin') }}" class="apple-button">
                <i class="fas fa-arrow-left"></i> 返回管理
            </a>
        </div>
        <div class="theme-switcher" style="z-index: 1;">
            <button id="theme-toggle" class="apple-button">
                <i class="fas fa-moon"></i> 切换主题
            </button>
        </div>
        <div class="nav-right" style="overflow: visible; position: relative; z-index: 101;">
            {% if session.get('logged_in') %}
            <a href="{{ url_for('auth.admin_logout') }}" class="apple-button" style="position: relative; z-index: 102; display: flex; align-items: center;">
                <i class="fas fa-sign-out-alt"></i> 登出
            </a>
            {% else %}
            <a href="{{ url_for('auth.admin_login') }}" class="apple-button">
                <i class="fas fa-sign-in-alt"></i> 登录
            </a>
            {% endif %}
        </div>
    </div>
    <header class="blog-header">
        <div class="header-content">
            <h1>{% if post %}编辑{% else %}新建{% endif %}文章</h1>
        </div>
    </header>

    <main class="editor-container">
        <form method="POST" action="{{ url_for('admin.edit_post', slug=post.slug) if post else url_for('admin.new_post') }}" class="editor-form" enctype="multipart/form-data">
            <input type="hidden" name="csrf_token" value="{{ csrf_token() }}">

            <div class="form-group">
                <label for="title">
                    <i class="fas fa-heading"></i> 标题
                </label>
                <input type="text" id="title" name="title"
                       value="{{ post.title if post }}"
                       placeholder="请输入文章标题" required>
            </div>

            <div class="form-group">
                <label for="content">
                    <i class="fas fa-edit"></i> 内容
                </label>
                <div id="editor"></div>
                <textarea id="content" name="content" style="display:none">
                    {{ post.content if post }}
                </textarea>
            </div>

            <div class="form-actions">
                <button type="submit" class="apple-button primary">
                    <i class="fas fa-save"></i> 保存文章
                </button>
                {% if post %}
                <a href="{{ url_for('admin.delete_post_route', slug=post.slug) }}"
                   class="apple-button danger"
                   onclick="return confirm('确定要删除这篇文章吗？')">
                    <i class="fas fa-trash"></i> 删除
                </a>
                {% endif %}
            </div>
        </form>
    </main>

    <script src="https://cdn.jsdelivr.net/npm/jquery@3.6.0/dist/jquery.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/tui-editor@1.4.10/dist/tui-editor-Editor-full.min.js"></script>
    <script>
        const editor = new tui.Editor({
            el: document.querySelector('#editor'),
            initialEditType: 'markdown',
            previewStyle: 'vertical',
            height: '500px',
            initialValue: document.getElementById('content').value.trim(),
            exts: ['markdown'],  // 强制使用Markdown模式
            hooks: {
                addImageBlobHook: (blob, callback) => {
                    const formData = new FormData();
                    formData.append('image', blob);

                    // 添加CSRF token
                    const csrfToken = document.querySelector('input[name="csrf_token"]').value;
                    formData.append('csrf_token', csrfToken);

                    // 显示上传状态
                    const uploadStatus = document.createElement('div');
                    uploadStatus.className = 'upload-status';
                    uploadStatus.innerHTML = '<i class="fas fa-spinner fa-spin"></i> 上传中...';
                    document.body.appendChild(uploadStatus);

                    fetch('/upload_image', {
                        method: 'POST',
                        body: formData,
                        headers: {
                            'X-Requested-With': 'XMLHttpRequest'
                        }
                    })
                    .then(response => {
                        if (!response.ok) {
                            throw new Error('Network response was not ok');
                        }
                        // 取消上传状态
                        uploadStatus.remove();
                        return response.json();
                    })
                    .then(data => {
                        if(data.success) {
                            // 确保URL是相对路径
                            let imageUrl = data.url;
                            if (imageUrl.startsWith('http')) {
                                const urlObj = new URL(imageUrl);
                                imageUrl = urlObj.pathname;
                            }
                            callback(imageUrl, data.alt || 'image');
                        } else {
                            uploadStatus.innerHTML = `<i class="fas fa-exclamation-circle"></i> 上传失败: ${data.message}`;
                        setTimeout(() => uploadStatus.remove(), 3000);
                        }
                    })
                    .catch(error => {
                        console.error('Error:', error);
                        uploadStatus.innerHTML = `<i class="fas fa-exclamation-circle"></i> 上传错误: ${error.message}`;
                        setTimeout(() => uploadStatus.remove(), 3000);
                    });
                }
            }
        });

        $('form').submit(function() {
            // 确保获取的是原始Markdown内容
            const markdownContent = editor.getMarkdown();
            $('#content').val(markdownContent);
            return true;
        });
    </script>
<script>
        // 主题切换功能
        const themeToggle = document.getElementById('theme-toggle');
        const body = document.body;

        // 检查本地存储的主题偏好
        if (localStorage.getItem('theme') === 'dark') {
            body.classList.add('dark-theme');
            themeToggle.innerHTML = '<i class="fas fa-sun"></i> 切换主题';
        }

        themeToggle.addEventListener('click', () => {
            body.classList.toggle('dark-theme');
            const isDark = body.classList.contains('dark-theme');
            localStorage.setItem('theme', isDark ? 'dark' : 'light');
            themeToggle.innerHTML = isDark
                ? '<i class="fas fa-sun"></i> 切换主题'
                : '<i class="fas fa-moon"></i> 切换主题';
        });
    </script>
</body>
</html>